package org.jeecg.modules.demo.qualityOrder.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.pubuyorder.service.IPuBuyOrderService;
import org.jeecg.modules.demo.qualityOrder.entity.PuBuyOrderToQualityOrder;
import org.jeecg.modules.demo.qualityOrder.entity.PuQualityOrder;
import org.jeecg.modules.demo.qualityOrder.service.IPuBuyOrderToQualityOrderService;
import org.jeecg.modules.demo.qualityOrder.service.IPuQualityOrderService;
import org.jeecg.modules.demo.warehouseorder.service.IWarehouseOrderService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

 /**
 * @Description: 采购订单
 * @Author: jeecg-boot
 * @Date:   2021-11-26
 * @Version: V1.0
 */
@Api(tags="采购订单")
@RestController
@RequestMapping("/qualityOrder/puBuyOrderToQualityOrder")
@Slf4j
public class PuBuyOrderToQualityOrderController extends JeecgController<PuBuyOrderToQualityOrder, IPuBuyOrderToQualityOrderService> {

	@Autowired
	private IPuBuyOrderToQualityOrderService puBuyOrderToQualityOrderService;

	@Autowired
	private IPuQualityOrderService puQualityOrderService;

	@Autowired
	private IWarehouseOrderService warehouseOrderService;

	@Autowired
	private IPuBuyOrderService puBuyOrderService;

	 @Autowired
	 private ISysBaseAPI sysBaseAPI;




	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param puBuyOrderToQualityOrder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "采购订单-分页列表查询")
	@ApiOperation(value="采购订单-分页列表查询", notes="采购订单-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(PuBuyOrderToQualityOrder puBuyOrderToQualityOrder,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		try{
			QueryWrapper<PuBuyOrderToQualityOrder> queryWrapper = QueryGenerator.initQueryWrapper(puBuyOrderToQualityOrder, req.getParameterMap());
			queryWrapper.ge("SHENHE",1);
			queryWrapper.eq("SHANCHU",0);
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			List<String> list = sysBaseAPI.getDepartNamesByUsername(sysUser.getUsername());
			String deptName= null;
			if(list.size()>=1){
				deptName = list.get(0);
			}
			if(sysUser.getUsername().equals("admin") || sysUser.getUsername().equals("administrator")||deptName.equals("财务部")){
				Page<PuBuyOrderToQualityOrder> page = new Page<PuBuyOrderToQualityOrder>(pageNo, pageSize);
				IPage<PuBuyOrderToQualityOrder> pageList = puBuyOrderToQualityOrderService.page(page, queryWrapper);
				return Result.OK(pageList);
			}
			if( sysUser.getUserIdentity()== 2 ){
				queryWrapper.eq("DEPARTMENT",sysUser.getDepartIds());
			}else {
				queryWrapper.eq("PO_STAFF",sysUser.getId());
			}
			Page<PuBuyOrderToQualityOrder> page = new Page<PuBuyOrderToQualityOrder>(pageNo, pageSize);
			IPage<PuBuyOrderToQualityOrder> pageList = puBuyOrderToQualityOrderService.page(page, queryWrapper);
			return Result.OK(pageList);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(300,"网络故障！");
		}
	}

	/**
     *   添加
     * @param puBuyOrderToQualityOrder
     * @return
     */
    @AutoLog(value = "采购订单-添加")
    @ApiOperation(value="采购订单-添加", notes="采购订单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody PuBuyOrderToQualityOrder puBuyOrderToQualityOrder) {
        puBuyOrderToQualityOrderService.save(puBuyOrderToQualityOrder);
        return Result.OK("添加成功！");
    }

    /**
     *  编辑
     * @param puBuyOrderToQualityOrder
     * @return
     */
    @AutoLog(value = "采购订单-编辑")
    @ApiOperation(value="采购订单-编辑", notes="采购订单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody PuBuyOrderToQualityOrder puBuyOrderToQualityOrder) {
        puBuyOrderToQualityOrderService.updateById(puBuyOrderToQualityOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "采购订单-通过id删除")
    @ApiOperation(value="采购订单-通过id删除", notes="采购订单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        puBuyOrderToQualityOrderService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "采购订单-批量删除")
    @ApiOperation(value="采购订单-批量删除", notes="采购订单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.puBuyOrderToQualityOrderService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PuBuyOrderToQualityOrder puBuyOrderToQualityOrder) {
        return super.exportXls(request, puBuyOrderToQualityOrder, PuBuyOrderToQualityOrder.class, "采购订单");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PuBuyOrderToQualityOrder.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-质检单-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "质检单-通过主表ID查询")
	@ApiOperation(value="质检单-通过主表ID查询", notes="质检单-通过主表ID查询")
	@GetMapping(value = "/listPuQualityOrderByMainId")
	@PermissionData(pageComponent="yunxiao/qualityOrder/PuQualityOrderList")
    public Result<?> listPuQualityOrderByMainId(PuQualityOrder puQualityOrder,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
       try{
		   QueryWrapper<PuQualityOrder> queryWrapper = QueryGenerator.initQueryWrapper(puQualityOrder, req.getParameterMap());
		   queryWrapper.eq("SHANCHU",0);
		   Page<PuQualityOrder> page = new Page<PuQualityOrder>(pageNo, pageSize);
		   IPage<PuQualityOrder> pageList = puQualityOrderService.page(page, queryWrapper);
		   return Result.OK(pageList);
	   }catch (Exception e){
       		e.printStackTrace();
       		return Result.error(300,"网络故障！");
	   }
    }


	 @PostMapping(value = "/getZJ")
	 public String getZJ(@RequestParam(name="str",required=true)String str){
		 Gson gson = new Gson();
		 Map map = new HashMap();
		 try{
			 PuQualityOrder qualityOrder = puQualityOrderService.getByQoNum(str);
			 map.put("code",200);
			 map.put("message","查询成功！");
			 map.put("zlsl",qualityOrder.getQoQuantity());
			 String json = gson.toJson(map);
			 return json;
		 }catch (Exception e){
			 e.printStackTrace();
			 map.put("code",500);
			 map.put("message","系统错误！");
			 String json = gson.toJson(map);
			 return json;
		 }
	 }

    @PostMapping(value = "/getZJDataList")
	 public String getZJDataList(@RequestParam(name="str",required=true)String str){
		 Gson gson = new Gson();
		 Map map = new HashMap();
		 try{
			 List<PuQualityOrder> puQualityOrders = puQualityOrderService.getZJDataList(str);
			 map.put("code",200);
			 map.put("message","查询成功！");
			 map.put("puQualityOrders",puQualityOrders);
			 String json = gson.toJson(map);
			 return json;
		 }catch (Exception e){
			 e.printStackTrace();
			 map.put("code",500);
			 map.put("message","系统错误！");
			 String json = gson.toJson(map);
			 return json;
		 }
	 }
	/**
	 * 生成质检单
	 * @param puQualityOrder
	 * @return
	 */
	@AutoLog(value = "质检单-添加")
	@ApiOperation(value="质检单-添加", notes="质检单-添加")
	@PostMapping(value = "/addPuQualityOrder")
	public Result<?> addPuQualityOrder(@RequestBody PuQualityOrder puQualityOrder,HttpServletRequest req) {
		try{
			if(puQualityOrder.getRealzb()==""||puQualityOrder.getRealzb()==null){
				return Result.error(300,"质检指标不能为空！");
			}
			if(puQualityOrder.getQoQuantity().doubleValue()<=0){
				return Result.error(300,"质检数量不能小于等于0！");
			}
			String tenantId = req.getHeader("tenant-id");
			if(puQualityOrderService.addPuQualityOrder(tenantId,puQualityOrder)){
				return Result.OK("成功！");
			}
			return Result.error(500,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	 /**
	  * 审核
	  * @param puQualityOrder
	  * @return
	  */
	 @AutoLog(value = "质检单-审核")
	 @ApiOperation(value="质检单-审核", notes="质检单-审核")
	 @PostMapping(value = "/checkPuQualityOrder")
	 public Result<?> checkPuQualityOrder(@RequestBody PuQualityOrder puQualityOrder) {
	 	 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(puQualityOrder.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
	 	 	if(puQualityOrder.getShenhe()==1){
	 	 		return Result.error(500,"已审核，无需重复审核！");
			}

	 	 	puQualityOrder.setSaleman(sysUser.getId());
	 	 	puQualityOrder.setShenhe(1);
	 	 	puQualityOrder.setShTime(new Date());
	 	 	puQualityOrderService.updateById(puQualityOrder);
	 	 	return Result.OK("审核成功!");
		 }catch (Exception e){
	 	 	e.printStackTrace();
	 	 	return Result.error(500,"系统错误！");
		 }
	 }
	 /**
	  * 弃审
	  * @param puQualityOrder
	  * @return
	  */
	 @AutoLog(value = "质检单-弃审")
	 @ApiOperation(value="质检单-弃审", notes="质检单-弃审")
	 @PostMapping(value = "/waiveCheckPuQualityOrder")
	 public Result<?> waiveCheckPuQualityOrder(@RequestBody PuQualityOrder puQualityOrder) {
		 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(puQualityOrder.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
		 	if(puQualityOrder.getShenhe()==0){
		 		return Result.error(300,"请先审核质检单！");
			}

		 	List<String> poOrders = warehouseOrderService.selectByPoOrder(puQualityOrder.getQoNum());
		 	if (!poOrders.isEmpty()){
		 		return Result.error(300,"已生成入库单，无法弃审！");
			}
			 puQualityOrder.setShTime(null);
			 puQualityOrder.setShenhe(0);
			 puQualityOrderService.updateById(puQualityOrder);
			 return Result.OK("弃审成功!");
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(500,"系统错误！");
		 }
	 }
    /**
	 * 编辑
	 * @param puQualityOrder
	 * @return
	 */
	@AutoLog(value = "质检单-编辑")
	@ApiOperation(value="质检单-编辑", notes="质检单-编辑")
	@PutMapping(value = "/editPuQualityOrder")
	public Result<?> editPuQualityOrder(@RequestBody PuQualityOrder puQualityOrder) {
		try{
			if(puQualityOrder.getShenhe()==1){
				return Result.error(300,"质检单已审核，无法编辑！");
			}

			if(puQualityOrderService.updateOrder(puQualityOrder)){
				return Result.OK("编辑成功!");
			}
			return Result.error(500,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}



	/**
	 * 通过id逻辑删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "质检单-通过id删除")
	@ApiOperation(value="质检单-通过id删除", notes="质检单-通过id删除")
	@DeleteMapping(value = "/deletePuQualityOrder")
	public Result<?> deletePuQualityOrder(@RequestParam(name="id",required=true) String id) {
		try {
			PuQualityOrder puQualityOrder = puQualityOrderService.getById(id);
			if(puQualityOrder.getShenhe()==1){
				return Result.error(300,"已审核，无法删除！");
			}
			if(puQualityOrderService.deletePuQualityOrder(puQualityOrder)){
				return Result.OK("删除成功!");
			}
			return  Result.error(300,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return  Result.error(500,"系统错误！");
		}
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "质检单-批量删除")
	@ApiOperation(value="质检单-批量删除", notes="质检单-批量删除")
	@DeleteMapping(value = "/deleteBatchPuQualityOrder")
	public Result<?> deleteBatchPuQualityOrder(@RequestParam(name="ids",required=true) String ids) {
	    this.puQualityOrderService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportPuQualityOrder")
    public ModelAndView exportPuQualityOrder(HttpServletRequest request, PuQualityOrder puQualityOrder) {
		 // Step.1 组装查询条件
		 QueryWrapper<PuQualityOrder> queryWrapper = QueryGenerator.initQueryWrapper(puQualityOrder, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<PuQualityOrder> pageList = puQualityOrderService.list(queryWrapper);
		 List<PuQualityOrder> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "质检单"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, PuQualityOrder.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("质检单报表", "导出人:" + sysUser.getRealname(), "质检单"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importPuQualityOrder/{mainId}")
    public Result<?> importPuQualityOrder(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<PuQualityOrder> list = ExcelImportUtil.importExcel(file.getInputStream(), PuQualityOrder.class, params);
				 for (PuQualityOrder temp : list) {
                    temp.setPoOrder(mainId);
				 }
				 long start = System.currentTimeMillis();
				 puQualityOrderService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.OK("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-质检单-end----------------------------------------------*/




}
